package com.jiyun.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiyun.mapper.PermissionsMapper;
import com.jiyun.mapper.RolePermissionsMapper;
import com.jiyun.model.xitong.Permissions;
import com.jiyun.model.xitong.RolePermissions;
import com.jiyun.service.IPermissionsService;
import com.jiyun.service.IRolePermissionsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-10-10
 */
@Service
public class PermissionsServiceImpl extends ServiceImpl<PermissionsMapper, Permissions> implements IPermissionsService {
    @Autowired
    PermissionsMapper permissionsMapper;
    @Autowired
    RolePermissionsMapper rolePermissionsMapper;

    @Autowired
    IRolePermissionsService rolePermissionsService;
    @Override
    public List<Permissions> findPermissions() {
        return permissionsMapper.selectList(null);
    }

    @Override
    public Integer[] findPermissionsByRoleId(Integer id) {
        //根据id查出当前role有那些权限
        LambdaQueryWrapper<RolePermissions> rolePermissionsLambdaQueryWrapper= new LambdaQueryWrapper<>();
        rolePermissionsLambdaQueryWrapper.eq(RolePermissions::getRoleId,id);
        List<RolePermissions> rolePermissionsList = rolePermissionsMapper.selectList(rolePermissionsLambdaQueryWrapper);
        Integer[] ids=new Integer[rolePermissionsList.size()];
        for (int i = 0; i < rolePermissionsList.size(); i++) {
            ids[i]=rolePermissionsList.get(i).getPermissionsId();
        }
        return ids;
    }

    @Override
    public Integer fenpei(Integer id, Integer[] ids) {
        //1.先根据roleid删除权限
        LambdaQueryWrapper<RolePermissions> rolePermissionsLambdaQueryWrapper= new LambdaQueryWrapper<>();
        rolePermissionsLambdaQueryWrapper.eq(RolePermissions::getRoleId,id);
        rolePermissionsMapper.delete(rolePermissionsLambdaQueryWrapper);
        //2.重新分配
        for (Integer permissionsId : ids ){
            RolePermissions rolePermissions1 = new RolePermissions();
            rolePermissions1.setRoleId(id);
            rolePermissions1.setPermissionsId(permissionsId);
            rolePermissionsMapper.insert(rolePermissions1);
        }
        return 0;
    }
}
